package ar.Location.Api.Eventful;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import ar.Location.Constant.Define;
import ar.Location.PlaceObject.Place;

public class EventfulHandler extends DefaultHandler {

	boolean is_entered_event_TAG = false;
	boolean is_entered_medium_TAG = false;

	EventfulPlace ePlace = null;
	ArrayList<Place> listPlaces = null;
	StringBuffer stringBuffer = new StringBuffer();

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		listPlaces = new ArrayList<Place>();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub

		stringBuffer.setLength(0);

		if (localName.equals("event")) {
			is_entered_event_TAG = true;
			ePlace = new EventfulPlace(Define.DS_EVENTFUL);
		}
		if (localName.equals("medium")) {
			is_entered_medium_TAG = true;
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		stringBuffer.append(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		String innerText = stringBuffer.toString().trim();

		if (is_entered_event_TAG) {
			if (localName.equals("title")) {
				ePlace.name = innerText;
			}
			if (localName.equals("venue_address")) {
				ePlace.address = innerText;
			}
			if (localName.equals("latitude")) {
				ePlace.latitude = innerText;
			}
			if (localName.equals("longitude")) {
				ePlace.longitude = innerText;
			}
			if (localName.equals("description")) {
				ePlace.description = innerText;
			}
			if (localName.equals("start_time")) {
				ePlace.dateTime = innerText;
			}
			if (localName.equals("url")) {
				ePlace.websiteUrl = innerText;
			}
		}

		if (localName.equals("url")) {
			if (is_entered_medium_TAG) {
				ePlace.imageUrl = innerText;
			}
		}

		if (localName.equals("event")) {
			if (ePlace.description != null) {
				if (ePlace.description.trim().length() > 0) {
					listPlaces.add(ePlace);
				}
			}
			is_entered_event_TAG = false;
		}

		if (localName.equals("medium")) {
			is_entered_medium_TAG = false;
		}
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}

	public ArrayList<Place> getListResults() {
		if (listPlaces != null && listPlaces.size() > 0) {
			return listPlaces;
		}
		return null;
	}
}
